package com.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.chart.ChartFactory;
import com.chart.factory.PiePlotFactory;
import com.chart.vo.Chart;
import com.core.baseDao.extend.Pager;
import com.manager.KeywordManager;
import com.manager.VoteManager;
import com.model.Keyword;
import com.model.ModuleConstant;
import com.model.Vote;
import com.model.VoteOptions;
import com.opensymphony.xwork2.ActionSupport;
import com.util.ServletUtils;
import com.util.TimeUtil;

@ParentPackage("json-default")
@Results({ 
	@Result(name = "jsonResult", type = "json")
})
@Namespace("/user")
public class VoteAction extends ActionSupport {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3450735628523408953L;

	@Autowired
	private VoteManager voteManager;
	@Autowired
	private KeywordManager keywordManager;
	
	private Keyword keyword;
	
	public Keyword getKeyword() {
		return keyword;
	}

	public void setKeyword(Keyword keyword) {
		this.keyword = keyword;
	}

	public String add(){
		return "add";
	}
	
	public String addTo() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String ret = "";
		String token = ServletUtils.getToken();
		if(null == keyword) {
			return "index";
		}
		if(keyword.getId() == null){
			ret = "添加成功";
			String type = request.getParameter("type");
			keyword.getVote().setType(type);
			keyword.getVote().setCreateTime(TimeUtil.getDate());
			keyword.getVote().setStatus(Vote.VOTE_STATUS_I);
		}else{
			ret = "更新成功";
		}
		keyword.setModel(ModuleConstant.VOTE);
		keyword.getVote().setUpdateTime(TimeUtil.getDate());
		keyword.getVote().setToken(token);
		keyword.setToken(token);
		keyword.getVote().setKeyword(keyword);
		
		List<VoteOptions> ops = keyword.getVote().getVoteOptionList();
		for(VoteOptions op : ops){
			op.setVote(keyword.getVote());
		}

		try {
			keywordManager.saveOrUpdate(keyword);
		} catch (Exception e) {
			ret = "数据库出错，请与开发人员联系！";
			
			return "add";
		}finally{
			request.setAttribute("ret", ret);
		}
		
		return "index";
	}
	
	public String edit(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String voteId = request.getParameter("voteId");
		voteId = (null == voteId) ? "-1" : voteId;
		Integer iVoteId = Integer.parseInt(voteId);
		Vote vote = null;
		
		try {
			vote = (Vote)voteManager.findUnique("from Vote where id = ?", new Object[] {iVoteId});
			this.keyword = vote.getKeyword();
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
		}
		
		return "edit";
	}

	public String result(){
		ServletRequest request = ServletActionContext.getRequest();
		ChartFactory<Integer> chartFactory = new PiePlotFactory<Integer>();
		Chart<Integer> chart = new Chart<Integer>();
		
		String voteId = request.getParameter("voteId");
		voteId = (null == voteId) ? "-1" : voteId;
		Integer iVoteId = Integer.parseInt(voteId);
		Vote vote = null;
		Map<String, Integer> dataMap = new HashMap<String, Integer>();
		
		try {
			vote = (Vote)voteManager.findUnique("from Vote where id = ?", new Object[] {iVoteId});
			List<VoteOptions> list = vote.getVoteOptionList();
			for(VoteOptions vo : list) {
				dataMap.put(vo.getContent(), vo.getVoteCount());
			}
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
		}
		
		chart.setDataMap(dataMap);
		chart.setShowLegend(true);
		chart.setTitle("投票结果");
		chart.setWidth(500);
		chart.setHeight(300);
		try {
			chartFactory.createChart(chart);
		} catch (IOException e) {
			e.printStackTrace();
		}
		request.setAttribute("chartData", chart);
		
		return "result";
	}
	
	public String start(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String voteId = request.getParameter("voteId");
		
		updateStatus(new String[]{voteId}, Vote.VOTE_STATUS_S);
		
		return null;
	}
	
	public String end(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String voteId = request.getParameter("voteId");
		
		updateStatus(new String[]{voteId}, Vote.VOTE_STATUS_E);
		
		return null;
	}
	
	public String delete() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String strIds = request.getParameter("voteId");
		if(	StringUtils.isEmpty(strIds) ) {
			return null;
		}
		String []voteIds = strIds.split(",");
		//将vote记录的status置为“D”
		updateStatus(voteIds, Vote.VOTE_STATUS_D);
		
		return null;
	}
	
	/**
	 * 根据Id更新对应投票记录的状态位，并向请求返回Json结果。
	 * @param voteId
	 * @param status [Vote.Vote.VOTE_STATUS_I|Vote.VOTE_STATUS_S|Vote.VOTE_STATUS_D|Vote.VOTE_STATUS_E]
	 */
	private void updateStatus(String[] voteIds, char status) {
		HttpServletResponse response = ServletActionContext.getResponse();
		
		if(voteIds == null || voteIds.length == 0) {
			return ;
		}
		
		Vote vote = null;
		
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		StringBuffer strMsg = new StringBuffer();
		String type = null;
		try {
			if(1 == voteIds.length) {
				if(StringUtils.isEmpty(voteIds[0])) {
					type = "faile";
					strMsg.append("传入的ID值为空");
				} else {
					Integer iVoteId = Integer.parseInt(voteIds[0]);
					vote = (Vote) voteManager.findUnique("from Vote where id = ?", new Object[]{iVoteId});
					vote.setStatus(status);
					voteManager.saveOrUpdate(vote);
					type = "success";
					strMsg.append("操作成功");
				}
			} else {
				List<Vote> voteList = new ArrayList<Vote>();
				int deleteCount = 0;
				
				for(String voteId : voteIds) {
					if(! StringUtils.isEmpty(voteIds[0])) {
						Integer iVoteId = Integer.parseInt(voteId);
						
						vote = voteManager.find("from Vote where id = ?", iVoteId).get(0);
						vote.setStatus(status);
						voteList.add(vote);
						deleteCount ++;
					}
				}
				voteManager.saveOrUpdateAll(voteList);
				type = "success";
				strMsg.append("操作成功，成功删除 ").append(deleteCount).append(" 条记录");
			}
			
			
		} catch(NumberFormatException e) {
			type = "faile";
			strMsg.append("数据异常，请联系管理员");
		} catch(Exception e) {
			type = "faile";
			strMsg.append("操作数据库异常，请联系管理员");
		}finally {
			StringBuffer strBuf = new StringBuffer();
			strBuf.append("{\"type\" : \"" + type + "\"");
			strBuf.append(", \"msg\" : \"" + strMsg + "\"}");
			PrintWriter out = null;
			try {
				out = response.getWriter();
			} catch (IOException e) {
				e.printStackTrace();
			}
			out.write(strBuf.toString());
			out.flush();
			out.close();
		}
	}
	
	public String index() {
		ServletRequest request = ServletActionContext.getRequest();
		Pager page = new Pager();
		String p = request.getParameter("p");
		if (!StringUtils.isEmpty(p)) {
			page.setCurrPage(Integer.parseInt(p));
		}
		// Map session = ActionContext.getContext().getSession();
		// String token = (String)session.get("token");
		Map<String, Object> params = new HashMap<String, Object>();
		// params.put("token", token);
		params.put("model", ModuleConstant.VOTE);
		page = keywordManager.findByPage("from Keyword ", params, page);
		request.setAttribute("page", page);
		
		return "index";
	}
	
}
